package com.jeeplus.modules.api.utils;


import com.alibaba.druid.mock.MockCallableStatement;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MD5Util;
import com.jeeplus.common.utils.SpringContextHolder;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.net.HttpClientUtil;
import com.jeeplus.modules.api.service.ApiService;
import com.jeeplus.modules.member.entity.Member;
import com.jeeplus.modules.member.service.MemberService;
import com.jeeplus.modules.taokeorder.entity.TTaokeOrder;
import com.jeeplus.modules.taokeorder.service.TTaokeOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 拼多多
 * @author ws
 *
 */
@Component
public class PddUtils {

	//拼多多
	private static final String apkey = "9aead88d-60cc-40da-b118-b702749ae6e8";// 秘钥
	public static final String pdname = "17194370528";// 在本平台授权后的拼多多用户名
	private static final String client_id = "b585bf2fa72d46a28d0096eaca61d249";// POP分配给应用的client_id
	private static final String client_secret = "61bb49f1c53643a336929d4db1f8c83fd36d6468";// t
	public static final String router = "https://gw-api.pinduoduo.com/api/router?";// 生成多多进宝频道推广
	// 生成多多进宝频道推广本接口用于进行平台大促活动（如618、双十一活动）、平台优惠频道转链（电器城、限时秒杀等）
	public static final String urlgen = "pdd.ddk.resource.url.gen";
	// 多多进宝主题推广链接生成本接口用于推广进宝官方主题，用户可以点击您的推广链接进入主题商品集合页进入购买下单
	public static final String generate = "pdd.ddk.theme.prom.url.generate";
	//商品搜索
	public static final String searchgoods = "pdd.ddk.goods.search";
	//商品搜索
	public static final String recommend = "pdd.ddk.goods.recommend.get";
	//爆品推荐
	public static final String getpdditem = "pdd.ddk.top.goods.list.query";
	//  (重构版)获取商品详细信息
	public static final String getGoodsDetailInfo = "pdd.ddk.goods.detail";
	// 获取拼多多商品推广链接API
	public static final String getpdditemtgurl = "pdd.ddk.goods.promotion.url.generate";
	// 创建推广位接口
	public static final String docreatepddpid = "pdd.ddk.goods.pid.generate";
	// 按照更新时间段增量同步推广订单信息
	public static final String getincrementorderlist = "pdd.ddk.order.list.increment.get";
	// 按照支付时间段同步推广订单信息
	public static final String getrangeorderlist = "pdd.ddk.order.list.range.get";
	//查询订单详情
	public static final String getdetailOrder = "pdd.ddk.order.detail.get";
	//查询备案
	public static final String getauthority = "pdd.ddk.member.authority.query";
	//绑定备案10-生成绑定备案链接
	public static final String addbnprom = "pdd.ddk.rp.prom.url.generate";
	/**
	 * 日志对象
	 */
	private static Logger logger = LoggerFactory.getLogger(PddUtils.class);
	private static TTaokeOrderService tTaokeOrderService = SpringContextHolder.getBean(TTaokeOrderService.class);
	public static void main(String[] args) {

//		Map<String, String> params1 = Maps.newHashMap();
//		Map<String, String> params = Maps.newHashMap();
//		Map<String, String> params3 = Maps.newHashMap();
//		Map<String, String> params10 = Maps.newHashMap();
//		params.put("channel_type","10");
//		params.put("p_id_list", "['9191823_125476409']");
//		params.put("custom_parameters", "['uid':'E7CC6C17939B4F8E831D7635F0AC892D','sid':'111']");
//		JSONObject jsonObject2 = PddUtils.duoduorouterAPI(PddUtils.router, PddUtils.addbnprom, params);
//		JSONObject url= (JSONObject) jsonObject2.getJSONObject("rp_promotion_url_generate_response").getJSONArray("url_list").get(0);
//		System.out.println(jsonObject2);
//		System.out.println("________________________________________________________________________");
//		params10.put("pid","9191823_125476409");
//		params10.put("custom_parameters", "['uid':'E7CC6C17939B4F8E831D7635F0AC892D','sid':'111']");
//		JSONObject jsonObject10 = PddUtils.duoduorouterAPI(PddUtils.router, PddUtils.getauthority, params10);
//		System.out.println(jsonObject10);
//		System.out.println("________________________________________________________________________");
//		params1.put("sort_type","0");
//		params1.put("with_coupon","false");
//		params1.put("page","1");
//		params1.put("keyword", "红糖");
//		params1.put("page_size","10");
//		params1.put("pid","9191823_175904824");
//		params1.put("custom_parameters", "['uid':'E7CC6C17939B4F8E831D7635F0AC892D','sid':'111']");
//		JSONObject jsonObject1 = PddUtils.duoduorouterAPI(PddUtils.router, PddUtils.searchgoods, params1);
//		System.out.println(jsonObject1);
//		System.out.println("________________________________________________________________________");
//活动url
//搜索接口
//		Map<String, String> params1 = Maps.newHashMap();
//		System.out.println("________________________________________________________________________");
//		StringBuilder goodsid = new StringBuilder();
//		goodsid.append("115454823275");
//		String goodsids = goodsid.toString();
//		String[] array = goodsids.split(",");
//		for (int j = 0; j < array.length; j++) {
//			params1.put("sort_type","0");
//			params1.put("with_coupon","false");
//			params1.put("page","1");
//			params1.put("keyword",array[j]);
//			params1.put("page_size","10");
//			params1.put("pid","9191823_175904824");
//			params1.put("custom_parameters", "['uid':'E7CC6C17939B4F8E831D7635F0AC892D','sid':'111']");
//			JSONObject jsonObject1 = PddUtils.duoduorouterAPI(PddUtils.router, PddUtils.searchgoods, params1);
//			JSONArray jsonObject2=  jsonObject1.getJSONObject("goods_search_response").getJSONArray("goods_list");
//			if(jsonObject2.size()>0){
//				JSONObject jsonObject3= (JSONObject) jsonObject2.get(0);
//				String[] duan_sn = jsonObject3.getString("goods_sign").split("_");
//				int duan_sn_len=duan_sn.length;
//				System.out.println(jsonObject3.getString("goods_id")+" "+jsonObject3.getString("goods_sign")+" "+duan_sn[duan_sn_len-1]+"\n");
//			}else{
//				System.out.println(array[j]+" "+"为空"+"\n");
//				continue;
//			}
//		}
//定时更新接口
//		String start_update_times = "2019-10-16 10:37:14";
//		String end_update_times = "2021-03-16 13:56:51";
//		String last_order_id="";
//		while (true) {
//			Map<String, String> params = Maps.newHashMap();
//			params.put("start_time", start_update_times);// 订单开始时间
//			params.put("end_time", end_update_times);// 订单结束时间
//			params.put("last_order_id", last_order_id);// 第几页，默认1，1~100
//			params.put("page_size", "300");// 页大小，默认20，1~100
//			params.put("query_order_type", "1");// 默认推广订单
//			JSONObject jsonObject = PddUtils.duoduorouterAPI(PddUtils.router,PddUtils.getrangeorderlist, params);
//			System.out.println("拼多多官方返回数据：" + jsonObject.toString());
//			if (jsonObject.containsKey("order_list_get_response")) {
//				JSONObject dataObject = jsonObject.getJSONObject("order_list_get_response");
//				if (dataObject != null) {
//					JSONArray orderList = dataObject.getJSONArray("order_list");
//					if (orderList != null && orderList.size() > 0) {
//						for (int i = 0; i < orderList.size(); i++) {
//							JSONObject o = orderList.getJSONObject(i);
//							TTaokeOrder to = tTaokeOrderService.get(o.getString("order_sn"));
//							if(to!=null){
//								if(to.getItemId().equals(o.getString("goods_id"))){
//									to.setGoodsSign(o.getString("goods_sign"));
//									tTaokeOrderService.save(to);
//								}
//							}
//						}
//					}
//					last_order_id = dataObject.getString("last_order_id");
//					System.out.println("拼多多官方返回数据last_order_id：" + last_order_id);
//				}
//			} else {
//				break;
//			}
//		}
//		System.out.println("________________________________________________________________________");
	}
	/**
	 * 多多进宝
	 * @param url API接口路径
	 *            type 接口名字
	 * @param params 业务参数
	 * @return
	 */
	public static JSONObject duoduorouterAPI(String url, String type, Map<String, String> params) {
		params.put("client_id", client_id);
		params.put("type", type);
		long now = new Date().getTime();
		params.put("timestamp", String.valueOf(now/1000));
		if(params.containsKey("sign")){
			params.remove("sign");
		}
		String url2 =getDuoduoParams(params);
		String sign = client_secret+url2+client_secret;
		sign = MD5Util.md5(sign).toUpperCase();
		params.put("sign", sign);
		String resultString = HttpClientUtil.doPost(url,params);
		return StringUtils.isNotBlank(resultString) ? JSONObject.parseObject(resultString) : new JSONObject();
	}


	/***
	 * 处理参数
	 * */
	public static String getDuoduoParams(Map<String, String> map) {
		String result = "";
		try {
			Map<String, String> params = new TreeMap<String, String>(
					new Comparator<String>() {
						public int compare(String obj1, String obj2) {
							// 升序排序
							return obj1.compareTo(obj2);
						}
					});
			TreeMap<String, String> treeMap = new TreeMap<>(map);

			// 构造签名键值对的格式
			StringBuilder sb = new StringBuilder();
			Iterator<Map.Entry<String, String>> iterator = treeMap.entrySet().iterator();
			while (iterator.hasNext()) {
				Map.Entry<String, String> entry = iterator.next();
				String key = entry.getKey();
				String val = entry.getValue();
				sb.append(key).append(val);
			}
			result = sb.toString();
			System.out.println("sb:" + result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
